package com.info.provider.service.impl;

import com.info.provider.entity.UserInfo;
import com.info.provider.repository.UserInfoRepository;
import com.info.provider.service.UserInfoService;
import com.mars.app.exception.ErrorCodeMsg;
import com.mars.app.exception.SystemException;
import com.mars.app.utils.UUIDUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by pengshuo on 2018/1/3 17:30
 * Description:
 * Modified By:
 * Version:
 *
 * @author pengshuo
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private UserInfoRepository userInfoRepository;

    /**
     * 不存在 新增
     *
     * @param userInfo
     * @return
     * @throws SystemException
     */
    @Override
    public UserInfo create(UserInfo userInfo) throws SystemException {
        try {
            // is null 不存在 --> 新增 ；else 存在 --> 更新
            UserInfo result = userInfoRepository.findByOpenId(userInfo.getOpenId());
            if(result == null){
                logger.debug("新增 user {}",userInfo);
                // id
                userInfo.setUuid(UUIDUtil.userInfo());
                userInfo.setCreateDate(new Date());
                return userInfoRepository.insert(userInfo);
            }
        }catch (Exception e){
            logger.error("新增UserInfo 异常：{}",e);
            throw new SystemException(ErrorCodeMsg.DAO_OPERATE_ERROR,e);
        }
        return userInfo;
    }

    /**
     * 不存在 新增，存在 更新
     *
     * @param userInfo userInfo
     * @return UserInfo
     * @throws SystemException
     */
    @Override
    public UserInfo createOrUpdate(UserInfo userInfo) throws SystemException {
        try {
            // is null 不存在 --> 新增 ；else 存在 --> 更新
            UserInfo result = userInfoRepository.findByOpenId(userInfo.getOpenId());
            if(result == null){
                logger.debug("新增 user {}",userInfo);
                // id
                userInfo.setUuid(UUIDUtil.userInfo());
                userInfo.setCreateDate(new Date());
                return userInfoRepository.insert(userInfo);
            }else{
                userInfo.setUuid(result.getUuid());
                userInfo.setCreateDate(result.getCreateDate());
                userInfo.setUpdateDate(new Date());

                logger.debug("更新 user {}",userInfo);

                return userInfoRepository.save(userInfo);
            }
        }catch (Exception e){
            logger.error("新增或更新UserInfo 异常：{}",e);
            throw new SystemException(ErrorCodeMsg.DAO_OPERATE_ERROR,e);
        }
    }

}
